#!/bin/bash

set -e

sudo swapoff -a
sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab


if [ -f /etc/apt/sources.list.d/kubernetes.list ]; then
    rm /etc/apt/sources.list.d/kubernetes.list
fi
K8S_VERSION=1.33

curl -fsSL https://pkgs.k8s.io/core:/stable:/v$K8S_VERSION/deb/Release.key |  gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg

echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v$K8S_VERSION/deb/ /" |  tee /etc/apt/sources.list.d/kubernetes.list

 apt-get update
 apt-get install -y containerd kubelet kubeadm kubectl
 apt-mark hold kubelet kubeadm kubectl


if [ -f /etc/modules-load.d/k8s.conf ]; then
    rm /etc/modules-load.d/k8s.conf
fi

cat <<EOF > /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF

modprobe overlay
modprobe br_netfilter


if [ -f /etc/crictl.yaml ]; then
    rm /etc/crictl.yaml
fi

cat <<EOF > /etc/crictl.yaml
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF





# sysctl params required by setup, params persist across reboots

if [ -f /etc/sysctl.d/k8s.conf ]; then
    rm /etc/sysctl.d/k8s.conf
fi

cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward                 = 1
EOF

# Apply sysctl params without reboot
sysctl --system

mkdir -p /etc/containerd
containerd config default |  tee /etc/containerd/config.toml

sed -i 's/SystemdCgroup \= false/SystemdCgroup \= true/g' /etc/containerd/config.toml
systemctl daemon-reload
systemctl restart containerd